﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Framework.Client;
using System.Collections.ObjectModel;

namespace DatabaseSynchronizer {

    public partial class SelectFolder : BaseForm {

        public SelectFolder(string tfsURL) {

            _tfsUri = new Uri(tfsURL);
            InitializeComponent();
        }

        private void SelectFolder_Load(object sender, EventArgs e) {

            string errorMsg = string.Empty;
            

            var projects = TFSService.GetProjectCollection(out errorMsg);

            if (projects == null) {

                ErrorLabel.Text = errorMsg;
            }
            else if (projects.Count == 0) {

                ErrorLabel.Text = "No Project Collections Available / Accessible.";
            }
            else {

                LoadProjectNodes(TFSFolderTreeView.Nodes , projects);
            }
        }

        private void TFSFolderTreeView_BeforeExpand(object sender, TreeViewCancelEventArgs e) {

            var node = e.Node;
            string error = string.Empty;

            if (node.Nodes.Count == 1 && node.Nodes[0].Text == "empty") {
                
                node.Nodes.Clear();

                ReadOnlyCollection<CatalogNode> result = null;

                if (node.Parent == null) {    //Collection node

                    result = TFSService.GetProjectFolders(node.Text, out error);
                }
                else {

                    Guid nodeId = Guid.Parse(node.Name);

                    while (node.Parent != null) {
                        node = node.Parent;
                    }

                    Guid collectionId = Guid.Parse(node.Name);

                    result = TFSService.GetProjectFolders(collectionId, nodeId, out error);
                }

                LoadProjectNodes(e.Node.Nodes, result);
            }
        }

        private void LoadProjectNodes(TreeNodeCollection nodeCollection, ReadOnlyCollection<CatalogNode> projects) {

            TreeNode node = null;

            foreach (CatalogNode p in projects) {

                    node = new TreeNode(p.Resource.DisplayName, new TreeNode[] { new TreeNode("empty") });

                node.Name = p.Resource.Identifier.ToString();
                nodeCollection.Add(node);
            }
        }
    }
}
